package cn.jnetty.utils;
import com.google.protobuf.*;

import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 猪哥亮
 * @email 1030681978@qq.com
 * @date 2020/6/21 17:26
 * 描述：
 */
public class JnettyBufferSerializableUtil {
    private static Map<Class, Parser<MessageLite>> map = new HashMap<>();
    private static <M extends MessageLite> AbstractParser<M> doParser(Class<M> type) {
        if(map.containsKey(type)){
            return (AbstractParser<M>) map.get(type);
        }
        AbstractParser<M> abstractParser = new AbstractParser<M>() {
            @Override
            public M parsePartialFrom(
                    CodedInputStream input,
                    ExtensionRegistryLite extensionRegistry)
                     {
                try {
                    Constructor c = type.getDeclaredConstructor(CodedInputStream.class, ExtensionRegistryLite.class);
                    c.setAccessible(true);
                    M obj = (M) c.newInstance(input, extensionRegistry);
                    return obj;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        };
        map.put(type, (Parser<MessageLite>) abstractParser);
        return  abstractParser;
    }
    public static Object parser(Class type,byte[] buff) throws InvalidProtocolBufferException {
        AbstractParser mParser = doParser(type);
        return mParser.parseFrom(buff);
    }
    public static byte[] toByteArray(com.google.protobuf.Message.Builder builder){
        return builder.build().toByteArray();
    }
}
